<template>
	<div class="addBox">
		<div class="addBoxTop">
			<div v-if="detailsId">
				<span class="font_size20">会员等级详细</span>
			</div>
			<div v-else class="font_size20">会员等级</div>
		</div>
		<div class="addDiv" v-loading="sLoading">
			<el-form ref="form" :model="objectForm" :rules="objectRules" label-width="140px">
				<el-form-item label="使用云店" prop="shopid_yd">
					<el-select v-model="objectForm.shopid_yd" placeholder="请选择"
						:disabled="isDisabled || isDisbableInfo.type">
						<el-option v-for="item in getYunShopsList" :key="item.id" :label="item.name" :value="item.id">
						</el-option>
					</el-select>
				</el-form-item>
				<el-form-item label="等级名称" prop="title">
					<el-input v-model="objectForm.title" class="input-w" placeholder="请填写标题, 20个文字内" maxlength="20"
						show-word-limit :disabled="isDisabled"></el-input>
				</el-form-item>
				<el-form-item label="会员等级" prop="grade">
					<el-select v-model="objectForm.grade" placeholder="请选择"
						:disabled="isDisabled || isDisbableInfo.type">
						<el-option v-for="item in gradeLs" :key="item.value" :label="item.label" :value="item.value">
						</el-option>
					</el-select>
				</el-form-item>
				<el-form-item label="等级权益" prop="ptype">
					<el-radio-group v-model="objectForm.ptype" :disabled="isDisabled || isDisbableInfo.type"
						size="small" @change="changeIsone">
						<el-radio border :label="item.value" v-for="item in pTypeList">{{ item.label }}</el-radio>
					</el-radio-group>
				</el-form-item>
				<el-form-item label="折扣价格" prop="discount_r" v-if="objectForm.ptype == 2">
					<el-input v-model="objectForm.discount_r" placeholder="请填写折扣" :min="0" :max="100"
						style="width: 217px;" :disabled="isDisabled" @input="handlePriceInput"></el-input><span
						class="tip-text">(%)</span>
				</el-form-item>
				<el-form-item label="千人千价" prop="price_i" v-if="objectForm.ptype == 1">
					<div class="flex_row">
						<div>
							<span> 商品价格： </span>
							<el-select v-model="objectForm.price_i" placeholder="请选择"
								:disabled="isDisabled || isDisbableInfo.type">
								<el-option v-for="item in price_ls" :key="item.value" :label="item.label"
									:value="item.value">
								</el-option>
							</el-select>
						</div>
						<div class="ml30">
							<span> 项目价格： </span>
							<el-select v-model="objectForm.yy_price_i" placeholder="请选择"
								:disabled="isDisabled || isDisbableInfo.type">
								<el-option v-for="item in yy_price_ls" :key="item.value" :label="item.label"
									:value="item.value">
								</el-option>
							</el-select>
						</div>
					</div>
				</el-form-item>
				<el-form-item label="是否可购买" prop="isbuy">
					<div class="switchDiv flex_row">
						<el-switch v-model="objectForm.isbuy" :active-value="'1'" :inactive-value="'2'"
							:disabled="isDisabled || isDisbableInfo.type">
						</el-switch>
						<div v-if="objectForm.isbuy == 1" class="ml20">
							<span class="mr10">购买价格</span>
							<el-input v-model="objectForm.price" placeholder="请填写购买价格" :min="0" style="width: 217px;"
								:disabled="isDisabled" @input="handlePrice2Input"></el-input><span
								class="tip-text">(元)</span>
						</div>
					</div>
				</el-form-item>
				<el-form-item label="自动升级" prop="isup">
					<div class="switchDiv flex_row">
						<el-switch v-model="objectForm.isup" :active-value="'1'" :inactive-value="'2'"
							:disabled="isDisabled || isDisbableInfo.type">
						</el-switch>
						<div v-if="objectForm.isup == 1" class="ml20">
							<span class="mr10"> 升级条件 </span>
							<el-select v-model="objectForm.ch_up" placeholder="请选择"
								:disabled="isDisabled || isDisbableInfo.type">
								<el-option v-for="item in chUpList" :key="item.value" :label="item.label"
									:value="item.value">
								</el-option>
							</el-select>
						</div>
						<div v-if="objectForm.ch_up == 1 && objectForm.isup == 1" class="ml20">
							<el-input v-model="objectForm.v_up" placeholder="请填写购买价格" :min="0" style="width: 217px;"
								:disabled="isDisabled || isDisbableInfo.type" @input="handlePrice3Input">
							</el-input>
							<span class="tip-text">(元)</span>
						</div>
						<div v-if="(objectForm.ch_up == 2 || objectForm.ch_up == 3) && objectForm.isup == 1" class="ml20">
							<el-input-number v-model="objectForm.v_up" controls-position="right" :min="0" :max="99999"
								:precision="0" :disabled="isDisabled || isDisbableInfo.type"
								class="el-input-xnumber-box">
							</el-input-number>
							<span class="tip-text">( {{ objectForm.ch_up == 2 ? '单' : '人' }})</span>
						</div>
					</div>
				</el-form-item>
				<el-form-item label="会员状态" prop="ishow">
					<div class="switchDiv">
						<el-switch v-model="objectForm.ishow" :active-value="'1'" :inactive-value="'2'"
							:disabled="isDisabled || isDisbableInfo.type">
						</el-switch>
					</div>
					<div class="flex_row" v-if="objectForm.ishow == 1">
						<div class="object-box flex_row">
							<span class="mr10">会员图标</span>
							<UploadPhotos :list="u_icon_arr" :limit="1"
								@update:list="updatePhotoQrCodeList('u_icon', $event)" />
						</div>
						<div class="object-box flex_row ml20">
							<span class="mr10">会员背景</span>
							<UploadPhotos :list="u_bimg_arr" :limit="1"
								@update:list="updatePhotoQrCodeList('u_bimg', $event)" />
						</div>
					</div>
				</el-form-item>
				<el-form-item :label="'会员权益'" prop="isr">
					<div class="switchDiv">
						<el-switch v-model="objectForm.isr" :active-value="'1'" :inactive-value="'2'"
							:disabled="isDisabled || isDisbableInfo.type">
						</el-switch>
					</div>
					<div class="pl-box" v-if="objectForm.isr == 1">
						<div class="flex_row mb10 mt10" v-for="(item, index) in objectForm.r_m">
							<div class="label-box flex_row felx1">
								<div class="flex_row">
									<span class="mr10">权益图标</span>
									<UploadPhotos :list="item.iconArr" :limit="1"
										@update:list="updatePhotoList(index, $event)" />
								</div>
								<div class="flex_row ml30">
									<span class="mr10">权益标题</span>
									<el-input style="width: 200px;" v-model="item.title" placeholder="请填写权益标题"
										show-word-limit></el-input>
								</div>
								<div class="flex_row ml30 felx1" style="flex: 1;">
									<div class="" style="width: 5rem;">权益内容</div>
									<el-input v-model="item.txt" placeholder="请填写权益内容" show-word-limit></el-input>
								</div>
								<div class="object-item-delete-box" v-if="objectForm.r_m.length > 1"
									@click="deleteObject(index)">
									<i class="el-icon-delete" style="color: #c00;"></i>
								</div>
							</div>
							<div class="add-object ml20">
								<el-button type="primary" v-if="index == objectForm.r_m.length - 1" @click="addObject" icon="el-icon-plus" circle></el-button>
							</div>
						</div>
					</div>
				</el-form-item>
				<el-form-item label="会员规则" prop="rule_txt">
					<el-input type="textarea" v-model="objectForm.rule_txt" class="input-w" placeholder="请填写会员规则"
						show-word-limit :disabled="isDisabled"></el-input>
				</el-form-item>
				<el-form-item label="启用" prop="value1">
					<div class="switchDiv">
						<el-switch v-model="objectForm.status" :disabled="isDisabled" :active-value="'1'"
							:inactive-value="'2'"></el-switch>
					</div>
				</el-form-item>
			</el-form>
		</div>
		<div class="addDivBtn">
			<div class="disabled-btn" v-if="isDisabled" @click="createActivity">提交</div>
			<div class="acvite-btn" v-else @click="createActivity">提交</div>
			<div class="back-btn" @click="goBack">返回</div>
		</div>
	</div>
</template>

<script setup>
import { ref, onMounted, defineProps, defineEmits, getCurrentInstance, watch, computed, defineExpose } from '@vue/composition-api'
import config from "@/js/conf/Config.js"
import { priceInput } from '@/utils/common.js'
import UploadPhotos from "@/components/commV2/UploadPhotos/index.vue"
import { pTypeList, chUpList } from "@/utils/dict.js"

// 获取当前组件实例
const { proxy } = getCurrentInstance()
const props = defineProps({
	getYunShopList: {
		type: Array,
		default: () => [],
	},
	detailID: {
		type: String,
		default: "",
	},
	// 如果是编辑页面，设置某些值不能编辑
	isDisbableInfo: {
		type: Object,
		default: () => ({
			type: false,
		}),
	},
})
const emit = defineEmits(['addTpBmFun'])
const form = ref(null)
const sLoading = ref(false)

// 图片列表  photoList 只接受2个参数  url 和 name
const updatePhotoList = (index, newList) => {
	objectForm.value.r_m[index].iconArr = newList
}

// State
const objectForm = ref({
	act: "add",
	id: "",
	shopid_yd: "",
	grade: "",
	discount_r: 0,
	type: "",
	price_i: '',
	yy_price_i: '',
	title: "",
	ptype: '2',
	isbuy: '1',
	isup: '1',
	price: 0,
	ishow: '1',
	isr: '1',
	r_m: [
		{ icon: '', iconArr: [], title: '', txt: '' }
	],
	ch_up: '',
	v_up: 0,
	txt_info: "",
	txt_rule: "",
	status: '1',
})

const objectRules = ref({
	shopid_yd: [
		{ required: true, message: '请选择云店', trigger: 'change' }
	],
	title: [
		{ required: true, message: '请输入投票/报名标题', trigger: 'blur' },
	],
	grade: [
		{ required: true, message: '请选择会员等级', trigger: 'change' }
	],
	ptype: [
		{ required: true, message: '请选择会员权益', trigger: 'change' }
	],
	discount_r: [
		{ required: true, message: '请输入折扣价格', trigger: 'blur' },
	],
	price_i: [
		{ required: true, message: '请输入会员价格', trigger: 'blur' },
	],
	yy_price_i: [
		{ required: true, message: '请输入会员价格', trigger: 'blur' },
	],
	price: [
		{ required: true, message: '请输入会员价格', trigger: 'blur' },
	],
})

const getYunShopsList = computed(() => {
	return props.getYunShopList
})

const restFun = () => {
	objectForm.value.id = ""
	objectForm.value.status = '2'
	form.value?.resetFields()
	objectForm.value = {
		act: "add",
		id: "",
		shopid_yd: "",
		grade: "",
		discount_r: 0,
		type: "",
		price_i: '',
		yy_price_i: '',
		title: "",
		ptype: '2',
		isbuy: '1',
		isup: '1',
		price: 0,
		ishow: '1',
		u_icon: '',
		u_bimg: '',
		isr: '1',
		r_m: [
			{ icon: '', iconArr: [], title: '', txt: '' }
		],
		ch_up: '',
		v_up: 0,
		txt_info: "",
		txt_rule: "",
		status: '1',
	}
	u_icon_arr.value = ref([])
	u_bimg_arr.value = ref([])
}

const addObject = () => {
	if (isDisabled.value) return
	objectForm.value.r_m.push({
		icon: '',
		iconArr: [],
		txt: '',
		title: "",
	})
}

const deleteObject = (index) => {
	objectForm.value.r_m.splice(index, 1)
}

const submitForm = async () => {
	const valid = await form.value?.validate()
	if (valid) {
		if (!validateSn()) {
			return
		}
		const params = {
			...objectForm.value,
		}
		params.r_m = params.r_m.map(item => {
			return {
				icon: item.iconArr[0]?.url || '',
				txt: item.txt,
				title: item.title,
			}
		})
		params.u_icon = u_icon_arr.value.length > 0 ? u_icon_arr.value.map(item => item.url).join(',') : ''
		params.u_bimg = u_bimg_arr.value.length > 0 ? u_bimg_arr.value.map(item => item.url).join(',') : ''
		const res = await proxy.$api({ url: config.yx_ugd_event_save, data: params })
		if (res.status == 1) {
			proxy.$message.success(res?.msg || '操作成功')
			emit("addTpBmFun", {
				type: objectForm.value.act,
			})
		} else {
			proxy.$message.error(res?.msg || '操作失败')
		}
	}
}

const validateSn = () => {
	let formData = objectForm.value
	if (formData.isbuy == 1 && formData.price <= 0) {
		proxy.$message.error('请输入购买价格')
		return false
	}
	if (formData.isup == 1 && formData.ch_up < 1 && formData.v_up <= 0) {
		proxy.$message.error('请选择升级条件及填写条件')
		return false
	}
	if (formData.ishow == 1 && u_icon_arr.value.length == 0 && u_bimg_arr.value.length == 0) {
		proxy.$message.error('请上传图标')
		return false
	}
	if (formData.isr == 1 && objectForm.value.r_m.length > 0) {
		let ispass = true
		objectForm.value.r_m.forEach(item => {
			if (!item.iconArr[0]?.url) {
				proxy.$message.error('请添加权益图标')
				ispass = false
			}
		})
		return ispass
	}
	return true
}

const u_icon_arr = ref([])
const u_bimg_arr = ref([])
const updatePhotoQrCodeList = (type, newList) => {
	if (type == 'u_icon') {
		u_icon_arr.value = newList
	} else if (type == 'u_bimg') {
		u_bimg_arr.value = newList
	}
}

const createActivity = () => {
	submitForm("form")
}

const goBack = () => {
	emit("backFun", 'back')
}

// 获取详情
const getDetail = async () => {
	sLoading.value = true
	const res = await proxy.$api({ url: config.yx_ugd_event_info, data: { id: props.detailID } }).finally(() => {
		setTimeout(() => {
			sLoading.value = false
		}, 200)
	})
	if (res.status === 1 && res.data) {
		const data = res.data?.info
		objectForm.value = {
			...data,
			act: "edt",
			r_m: data.r_m.map(vm => {
				return {
					...vm,
					iconArr: [
						{
							url: vm.icon
						}
					]
				}
			})
		}
		u_icon_arr.value = data.u_icon ? [{ url: data.u_icon }] : []
		u_bimg_arr.value = data.u_bimg ? [{ url: data.u_bimg }] : []
	}
}

// 获取级别
const gradeLs = ref([])
const getGradeLs = async () => {
	const res = await proxy.$api({ url: config.yx_ugd_grade_ls, data: {} }).finally(() => { })
	if (res.status === 1 && res.data) {
		// 将获取到的数据赋值到 objectForm
		gradeLs.value = res?.data?.grade_ls?.map(item => ({
			...item,
			label: item.title,
			value: item.id,
		}))
	}
}
getGradeLs()

// 获取价格
const price_ls = ref([])
const yy_price_ls = ref([])
const getPriceLs = async () => {
	const res = await proxy.$api({ url: config.yx_ugd_price_ls, data: {} }).finally(() => { })
	if (res.status === 1 && res.data) {
		let result = res.data
		price_ls.value = result.price_ls.map(item => ({
			...item,
			label: item.title,
			value: item.psort + '',

		}))
		yy_price_ls.value = result.yy_price_ls.map(item => ({
			...item,
			label: item.title,
			value: item.psort + '',
		}))
	}
}
getPriceLs()

// 修改 watch 实现
const detailsId = ref("")
watch(() => props.detailID, (newVal) => {
	console.log("detailID changed:", newVal)
	setTimeout(() => {
		if (newVal) {
			detailsId.value = newVal
			getDetail()
			form.value?.resetFields()
		}
		if (!newVal) {
			console.log("newValxxxx=", newVal)
			restFun()
		}
	}, 200)
}, { immediate: true })

// Lifecycle hooks
onMounted(() => {
})

// 添加计算属性
const isDisabled = computed(() => {
	const disabledStatus = ["7"]
	return disabledStatus.includes(objectForm.value.status)
})

const handlePriceInput = (value) => {
	objectForm.value.discount_r = priceInput(value)
}

const handlePrice2Input = (value) => {
	objectForm.value.price = priceInput(value)
}

const handlePrice3Input = (value) => {
	objectForm.value.v_up = priceInput(value)
}

defineExpose({
	restFun,
	objectForm
})

</script>

<style lang="scss" scoped>
.addBox {
	width: 100%;
	box-sizing: border-box;

	.addDivBtn {
		width: 100%;
		height: 60px;
		line-height: 60px;
		text-align: right;
		border-top: 1px solid #E4E7ED;

		>div {
			display: inline-block;
			background: #3388ff;
			font-size: 16px;
			height: 100%;
			color: #FFFFFF;
			text-align: center;
			padding: 0 20px;
			cursor: pointer;
			border-right: 1px solid #FFFFFF;

			&:last-child {
				border: none;
			}
		}

		.back-btn {
			background: #ece8e8;
			color: #333;
			border-right: 1px solid #ececec;
		}
	}

	.addBoxTop {
		width: 100%;
		height: 40px;
		border-bottom: 2px solid #E4E7ED;
		margin-bottom: 15px;
		display: flex;
		justify-content: space-between;
		align-items: center;
	}

	.addDiv {
		box-sizing: border-box;
		width: 100%;
		padding-right: 100px;
		height: calc(100vh - 57px - 70px);
		overflow-y: auto;

		.switchDiv {
			height: 40px;
			display: flex;
			align-items: center;
		}
	}
}

.tip-text {
	font-size: 12px;
	color: #666;
	margin-left: 10px;
}

.pl-box {
	padding: 10px 20px;
	background-color: #f5f4f4;
	border-radius: 6px;

	.label-box {
		position: relative;
		flex: 1;
		box-sizing: border-box;
		padding: 10px 30px 10px;
		border: 1px solid #DCDFE6;
		border-radius: 6px;
		gap: 10px;

		.object-item-delete-box {
			position: absolute;
			right: 0;
			top: 0;
			cursor: pointer;
			width: 20px;
			height: 20px;
			background-color: rgba(0, 0, 0, 0.1);
			border-bottom-left-radius: 6px;
			display: flex;
			align-items: center;
			justify-content: center;
			color: #FFFFFF;
			font-size: 12px;

			&:hover {
				background: rgba(0, 0, 0, 0.3);
			}
		}
	}
}

::v-deep .el-input-xnumber-box {
	width: 217px !important;

	.el-input__inner {
		text-align: left !important;
	}
}

.disabled-btn {
	opacity: 0.5;
	cursor: not-allowed;
	pointer-events: none;
}

.acvite-btn {
	opacity: 1;
	cursor: pointer;
}

::v-deep .el-icon-close:before {
	content: "\e6df";
}
</style>